// 模型训练管理模块
export class ModelTrainingManager {
    constructor() {
        this.modelListContainer = document.getElementById('model-list');
        this.trainingConfigContainer = document.getElementById('training-config');
        this.trainingProgressContainer = document.getElementById('training-progress');
        this.trainingLogContainer = document.getElementById('training-logs');
        this.systemResourcesContainer = document.getElementById('system-resources');
        
        this.initEventListeners();
    }

    // 初始化事件监听器
    initEventListeners() {
        // 训练按钮事件
        document.querySelectorAll('[data-train-model]').forEach(button => {
            button.addEventListener('click', (e) => {
                const modelId = e.target.dataset.trainModel;
                this.startTraining(modelId);
            });
        });

        // 训练配置切换
        document.querySelectorAll('[name="training-plan"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                this.updateTrainingPlanOptions(e.target.value);
            });
        });

        // 一键全部训练
        const trainAllButton = document.getElementById('train-all-models');
        if (trainAllButton) {
            trainAllButton.addEventListener('click', () => {
                this.startTrainingAll();
            });
        }
    }

    // 更新模型列表
    updateModelList(models) {
        if (!this.modelListContainer) return;

        const modelListHTML = `
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead>
                        <tr>
                            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                模型名称
                            </th>
                            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                状态
                            </th>
                            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                上次训练
                            </th>
                            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                准确率
                            </th>
                            <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                操作
                            </th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        ${models.map(model => `
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="font-medium text-gray-900">${model.name}</div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${this.getStatusClass(model.status)}">
                                        ${model.status}
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    ${model.lastTrained}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium ${this.getAccuracyClass(model.accuracy)}">
                                        ${model.accuracy}%
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <button data-train-model="${model.id}" class="text-blue-600 hover:text-blue-900 mr-3">
                                        训练
                                    </button>
                                    <button data-view-details="${model.id}" class="text-gray-600 hover:text-gray-900">
                                        详情
                                    </button>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;

        this.modelListContainer.innerHTML = modelListHTML;
        this.reattachEventListeners();
    }

    // 更新训练配置
    updateTrainingConfig(config) {
        if (!this.trainingConfigContainer) return;

        const configHTML = `
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div class="space-y-4">
                    <h4 class="font-semibold">训练方案</h4>
                    
                    <div class="space-y-2">
                        <div class="flex items-center">
                            <input type="radio" id="standard-plan" name="training-plan" value="standard" 
                                ${config.plan === 'standard' ? 'checked' : ''} class="h-4 w-4 text-blue-600">
                            <label for="standard-plan" class="ml-2 text-gray-700">标准训练</label>
                            <span class="ml-auto text-xs text-gray-500">约2小时</span>
                        </div>
                        
                        <div class="flex items-center">
                            <input type="radio" id="quick-plan" name="training-plan" value="quick" 
                                ${config.plan === 'quick' ? 'checked' : ''} class="h-4 w-4 text-blue-600">
                            <label for="quick-plan" class="ml-2 text-gray-700">快速训练</label>
                            <span class="ml-auto text-xs text-gray-500">约30分钟</span>
                        </div>
                        
                        <div class="flex items-center">
                            <input type="radio" id="deep-plan" name="training-plan" value="deep" 
                                ${config.plan === 'deep' ? 'checked' : ''} class="h-4 w-4 text-blue-600">
                            <label for="deep-plan" class="ml-2 text-gray-700">深度训练</label>
                            <span class="ml-auto text-xs text-gray-500">约6小时</span>
                        </div>
                        
                        <div class="flex items-center">
                            <input type="radio" id="custom-plan" name="training-plan" value="custom" 
                                ${config.plan === 'custom' ? 'checked' : ''} class="h-4 w-4 text-blue-600">
                            <label for="custom-plan" class="ml-2 text-gray-700">自定义训练</label>
                        </div>
                    </div>

                    <div id="custom-options" class="space-y-3 pl-6 ${config.plan === 'custom' ? '' : 'hidden'}">
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-sm text-gray-600 mb-1">批次大小</label>
                                <input type="number" id="batch-size" value="${config.batchSize || 32}" 
                                    class="w-full px-3 py-2 border rounded-lg">
                            </div>
                            <div>
                                <label class="block text-sm text-gray-600 mb-1">迭代次数</label>
                                <input type="number" id="epochs" value="${config.epochs || 100}" 
                                    class="w-full px-3 py-2 border rounded-lg">
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">学习率</label>
                            <input type="number" id="learning-rate" value="${config.learningRate || 0.001}" step="0.0001" 
                                class="w-full px-3 py-2 border rounded-lg">
                        </div>
                    </div>
                </div>

                <div class="space-y-4">
                    <h4 class="font-semibold">数据范围</h4>
                    
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">开始日期</label>
                            <input type="date" id="start-date" value="${config.startDate}" 
                                class="w-full px-3 py-2 border rounded-lg">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-600 mb-1">结束日期</label>
                            <input type="date" id="end-date" value="${config.endDate}" 
                                class="w-full px-3 py-2 border rounded-lg">
                        </div>
                    </div>
                    
                    <div class="space-y-2">
                        <label class="block text-sm text-gray-600 mb-1">股票范围</label>
                        <div class="flex space-x-4">
                            <div class="flex items-center">
                                <input type="radio" id="all-stocks" name="stock-range" value="all" 
                                    ${config.stockRange === 'all' ? 'checked' : ''} class="h-4 w-4 text-blue-600">
                                <label for="all-stocks" class="ml-2 text-gray-700">全部</label>
                            </div>
                            <div class="flex items-center">
                                <input type="radio" id="watchlist-stocks" name="stock-range" value="watchlist" 
                                    ${config.stockRange === 'watchlist' ? 'checked' : ''} class="h-4 w-4 text-blue-600">
                                <label for="watchlist-stocks" class="ml-2 text-gray-700">自选</label>
                            </div>
                            <div class="flex items-center">
                                <input type="radio" id="custom-stocks" name="stock-range" value="custom" 
                                    ${config.stockRange === 'custom' ? 'checked' : ''} class="h-4 w-4 text-blue-600">
                                <label for="custom-stocks" class="ml-2 text-gray-700">指定</label>
                            </div>
                        </div>
                    </div>

                    <div id="custom-stocks-input" class="space-y-2 ${config.stockRange === 'custom' ? '' : 'hidden'}">
                        <label class="block text-sm text-gray-600 mb-1">输入股票代码（以逗号分隔）</label>
                        <textarea id="stock-codes" class="w-full px-3 py-2 border rounded-lg" rows="3">${config.customStocks || ''}</textarea>
                    </div>
                </div>
            </div>
        `;

        this.trainingConfigContainer.innerHTML = configHTML;
        this.reattachEventListeners();
    }

    // 更新训练进度
    updateTrainingProgress(progress) {
        if (!this.trainingProgressContainer) return;

        const progressHTML = `
            <div class="space-y-4">
                <div class="flex items-center justify-between">
                    <h4 class="font-semibold">当前训练: ${progress.modelName}</h4>
                    <span class="text-sm text-gray-500">开始时间: ${progress.startTime}</span>
                </div>
                
                <div class="space-y-2">
                    <div class="flex justify-between text-sm">
                        <span>进度: ${progress.percentage}%</span>
                        <span>预计剩余时间: ${progress.remainingTime}</span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2.5">
                        <div class="bg-blue-600 h-2.5 rounded-full" style="width: ${progress.percentage}%"></div>
                    </div>
                </div>
                
                <div class="grid grid-cols-3 gap-4">
                    <div class="bg-gray-50 p-3 rounded-lg">
                        <div class="text-sm text-gray-600">CPU使用率</div>
                        <div class="text-lg font-semibold">${progress.cpuUsage}%</div>
                    </div>
                    <div class="bg-gray-50 p-3 rounded-lg">
                        <div class="text-sm text-gray-600">内存使用</div>
                        <div class="text-lg font-semibold">${progress.memoryUsage}</div>
                    </div>
                    <div class="bg-gray-50 p-3 rounded-lg">
                        <div class="text-sm text-gray-600">批次进度</div>
                        <div class="text-lg font-semibold">${progress.currentBatch}/${progress.totalBatches}</div>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3">
                    <button id="pause-training" class="btn-secondary">
                        暂停
                    </button>
                    <button id="stop-training" class="btn-danger">
                        停止
                    </button>
                </div>
            </div>
        `;

        this.trainingProgressContainer.innerHTML = progressHTML;
        this.reattachEventListeners();
    }

    // 更新训练日志
    updateTrainingLogs(logs) {
        if (!this.trainingLogContainer) return;

        const logsHTML = `
            <div class="space-y-2">
                <div class="flex justify-between items-center">
                    <h4 class="font-semibold">训练日志</h4>
                    <button id="view-full-logs" class="text-sm text-blue-600 hover:text-blue-800">
                        查看完整日志
                    </button>
                </div>
                
                <div class="bg-gray-50 p-3 rounded-lg h-48 overflow-y-auto font-mono text-sm">
                    ${logs.map(log => `
                        <div class="py-1 border-b border-gray-200 last:border-0">
                            <span class="text-gray-500">${log.timestamp}</span> - 
                            <span class="${this.getLogLevelClass(log.level)}">${log.message}</span>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;

        this.trainingLogContainer.innerHTML = logsHTML;
        this.reattachEventListeners();
    }

    // 更新系统资源信息
    updateSystemResources(resources) {
        if (!this.systemResourcesContainer) return;

        const resourcesHTML = `
            <div class="flex items-center space-x-4">
                <div class="flex items-center">
                    <span class="text-sm text-gray-600 mr-2">CPU:</span>
                    <div class="w-24 bg-gray-200 rounded-full h-2">
                        <div class="bg-blue-600 h-2 rounded-full" style="width: ${resources.cpu}%"></div>
                    </div>
                    <span class="ml-2 text-sm">${resources.cpu}%</span>
                </div>
                
                <div class="flex items-center">
                    <span class="text-sm text-gray-600 mr-2">内存:</span>
                    <div class="w-24 bg-gray-200 rounded-full h-2">
                        <div class="bg-green-600 h-2 rounded-full" style="width: ${resources.memory}%"></div>
                    </div>
                    <span class="ml-2 text-sm">${resources.memory}%</span>
                </div>
                
                <div class="flex items-center">
                    <span class="text-sm text-gray-600 mr-2">磁盘:</span>
                    <div class="w-24 bg-gray-200 rounded-full h-2">
                        <div class="bg-yellow-600 h-2 rounded-full" style="width: ${resources.disk}%"></div>
                    </div>
                    <span class="ml-2 text-sm">${resources.disk}%</span>
                </div>
                
                <div class="flex items-center">
                    <span class="text-sm text-gray-600 mr-2">温度:</span>
                    <span class="ml-2 text-sm ${resources.temperature < 70 ? 'text-green-600' : 'text-red-600'}">
                        ${resources.temperature}°C
                    </span>
                </div>
            </div>
        `;

        this.systemResourcesContainer.innerHTML = resourcesHTML;
    }

    // 开始训练指定模型
    startTraining(modelId) {
        // 调用后端API开始训练
        console.log(`开始训练模型: ${modelId}`);
        // 这里应该添加与后端API的交互代码
    }

    // 开始训练所有模型
    startTrainingAll() {
        // 调用后端API开始训练所有模型
        console.log('开始训练所有模型');
        // 这里应该添加与后端API的交互代码
    }

    // 更新训练方案选项
    updateTrainingPlanOptions(plan) {
        const customOptions = document.getElementById('custom-options');
        if (customOptions) {
            customOptions.classList.toggle('hidden', plan !== 'custom');
        }
    }

    // 重新附加事件监听器
    reattachEventListeners() {
        this.initEventListeners();
    }

    // 获取模型状态对应的样式类
    getStatusClass(status) {
        const classes = {
            '正常': 'bg-green-100 text-green-800',
            '警告': 'bg-yellow-100 text-yellow-800',
            '错误': 'bg-red-100 text-red-800',
            '训练中': 'bg-blue-100 text-blue-800'
        };
        return classes[status] || 'bg-gray-100 text-gray-800';
    }

    // 获取准确率对应的样式类
    getAccuracyClass(accuracy) {
        if (accuracy >= 80) return 'text-green-600';
        if (accuracy >= 70) return 'text-yellow-600';
        return 'text-red-600';
    }

    // 获取日志级别对应的样式类
    getLogLevelClass(level) {
        const classes = {
            'INFO': 'text-blue-600',
            'WARNING': 'text-yellow-600',
            'ERROR': 'text-red-600',
            'SUCCESS': 'text-green-600'
        };
        return classes[level] || 'text-gray-600';
    }
}